import numpy
import cv2 
import threading
import datetime
import time

class CvCamera(object):
    
    def __init__(self):
       self.cap = cv2.VideoCapture(r'D:\WorkData\VS2017Projects\TY_SolidBurningRate\TY.WinApp\bin\x86\Debug\CamVideo.avi')
       ret, frame = self.cap.read()
       self.cap.set(cv2.CAP_PROP_FOURCC,cv2.VideoWriter_fourcc('M','J','P','G'))
       #self.cap.set(cv2.CAP_PROP_FRAME_WIDTH,640)
       #self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT,480)
      
       #self.cap.set(cv2.CAP_PROP_FPS ,120)
       self.startFrame=0
       self.endFrame=0
       self.workFlag = True
       self.avg = None
       t = threading.Thread(target=self.__videoWork)
       t.start()


    def release(self):
       self.workFlag = False
       time.sleep(0.2)
       self.cap.release()

    def __videoWork(self):
       i = 0
       j=0
       d = None
       readyEnd=False
       while(self.workFlag):
          try:
              t = cv2.getTickCount()
              #time.sleep(0.01)
              ret, frame = self.cap.read()
              height, width, bytesPerComponent = frame.shape
              bytesPerLine = bytesPerComponent * width
              gray = cv2.cvtColor(frame,cv2.COLOR_BGR2GRAY)
              gray = cv2.GaussianBlur(gray,(25,25),0)
              #gray = gray[50:200,30:200]
              j+=1
              if(self.avg is None):
                  self.avg = gray.copy().astype("float")
              else:
                  if(i < 100):
                      i = i + 1
                      cv2.accumulateWeighted(gray,self.avg,0.5)
                      d = cv2.convertScaleAbs(self.avg)
                  frameDelta = cv2.absdiff(gray,d)
                  thresh = cv2.threshold(frameDelta, 50, 255,
                                         cv2.THRESH_BINARY)[1]
              
                  thresh = cv2.dilate(thresh, None, iterations=4)
                  (_, cnts,_) = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
                                               cv2.CHAIN_APPROX_SIMPLE)
                  # 遍历轮廓线
                  maxh=0
                  for c in cnts:
                      if cv2.contourArea(c) < 0:
                          continue
 
                      # 计算轮廓线的外框, 在当前帧上画出外框,并且更新文本
                      (x, y, w, h) = cv2.boundingRect(c)
                      #x = x + 30
                      #y = y + 50
                      cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 1)
                      if(self.startFrame==0):
                          self.startFrame=j
                      if(h>maxh):
                          maxh=h
                  if(maxh>=120):
                      readyEnd=True
                  #print(maxh)
                  if(readyEnd==True and maxh<120):
                      self.endFrame=j
                      print(self.startFrame)
                      print(self.endFrame)
                      break
          except :
              pass

